<template>
    <div>
        <Table :columns="columns" :paginatedData="paginatedData" :btnList="btnList" :btnListTable="btnListTable"
            :footerBtnList="footerBtnList" :isFixedColumn="true" :columnWidth="220" :isMore="false"
            :tableLoading="loading" :total="total" @pageSize="handlePageSize" @currentPage="handleCurrentPage">
            <!-- 条件组,插槽 -->
            <template #default>
                <el-form :inline="true" :model="formBtnList" class="demo-form-inline" @submit.native.prevent>
                    <!-- <el-form-item label="用户账号:">
              <el-input v-model="formBtnList.user" placeholder="请输入用户账号" />
            </el-form-item>
            <el-form-item label="用户名称:">
              <el-input v-model="formBtnList.name" placeholder="请输入用户名称" />
            </el-form-item> -->
                    <el-form-item label="">
                        <el-input v-model="formBtnList.admin_name" :prefix-icon="Search" placeholder="请输入姓名" />
                    </el-form-item>
                </el-form>
            </template>
        </Table>

        <!-- 弹窗 -->
        <DialogCom ref="dialogCom" :dialogVisible="dialogVisible" :btnLoading="btnLoading" :tableTitle="tableTitle"
            :formData="formData" :ruleForm="ruleForm" :rules="rules" @beforeClose="beforeClose"
            @dialogSwitch="dialogSwitch" @submitForm="submitForm" />
    </div>
</template>

<script setup lang='ts' name="adminMent">
import { ref, reactive, onMounted } from 'vue'
import type { FormRules } from 'element-plus'
import Table from '@/components/Table.vue';
import DialogCom from '@/components/DialogCom.vue';
import { require } from '@/utils/require';
import { Search } from '@element-plus/icons-vue'
import { auth, authDel, authAdd, authEdit, resetPassword } from '@/api/admin/index.ts'
// 表格相关 开始
const loading = ref(false)
const total = ref(0)

// 表头数据
const columns = ref([
    // { prop: 'admin_id', label: '账号ID', width: 130 },
    { prop: 'account', label: '用户名', width: 200 },
    { prop: 'admin_name', label: '姓名', width: 180 },
    { prop: 'role_id', label: '角色', width: 180, formatter: (row: any) => row.role_id == '1' ? '超级管理员' : row.role_id == '0' ? '管理员' : '' },
    { prop: 'phone', label: '电话', width: 230 },
    { prop: 'email', label: '邮箱', width: '' },
]);
// 表格数据
const paginatedData = ref([
    // { account: 'ID1', password: '12345678', adminName: '苏珊', email: 'singJumpRapBasketball@ikun.com', phone: '12345678901', created_at: '2023-10-05T14:48:00.000Z' },
    // { account: 'ID2', adminName: '打球被笑两年半', email: 'kunkun@ikun.com', created_at: '2023-10-05T14:48:00.000Z', profile_picture_url: require('@/assets/image/giegie.jpg') },
]);
// 查询条件
const formBtnList = reactive({
    admin_name: '',
    page_size: 10,
    page: 1,
})
// 查询点击事件
const handInquire = () => {
    loading.value = true
    auth(formBtnList, 'cn').then((res: any) => {
        if (res.code === 200) {
            if (res.data.total === 0) {
                paginatedData.value = []
                total.value = res.data.total
                ElMessage.error(`管理员信息不存在`)
                return
            }
            paginatedData.value = res.data.admin
            total.value = res.data.total
        } else {
            ElMessage.error(`管理员信息不存在`)
            paginatedData.value = []
        }
    }).catch((error: any) => {
        ElMessage.error(`请求错误: ${error.msg}`)
    }).finally(() => {
        loading.value = false
    })
}
interface RuleForm {
    admin_id: string
    account: string
    password: string
    adminName: string
    roleId: string
    email: string
    phone: string
    password2: string
}
// 表单数据
const ruleForm = reactive({})
// 重置表单方法
const resetForm = (initialData?: Partial<RuleForm>) => {
    Object.assign(ruleForm, {
        admin_id: '',
        account: '',
        password: '',
        adminName: '',
        roleId: '',
        email: '',
        phone: '',
        password2: '',
        ...(initialData || {}),
    });
};
// 重置
const handDerived = () => {
    // console.log('重置')
    formBtnList.admin_name = ''
    handInquire()
}
// 删除
const del = (row: object, index: number) => {
    ElMessageBox.confirm(
        '确定删除此项吗？',
        '删除',
        {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
        }
    ).then(() => {
        authDel(row.admin_id).then((res: any) => {
            if (res.code === 200) {
                ElMessage({
                    message: '删除成功',
                    type: 'success',
                })
            }
        }).catch((error: any) => {
            ElMessage.error(`请求错误: ${error.msg}`)
        }).finally(() => {
            handInquire()
        })
    })
}

// 选择框假数据
const jsOptions = ref([
    // { label: '超级管理员', value: '1' },
    { label: '管理员', value: '0' },
])
// 表单控件数据
let formData = reactive([
    { type: 'input', label: '用户名', prop: 'adminName', span: 24, placeholder: '请输入' },
    // { type: 'password', label: '密码', prop: 'password', span: 24, placeholder: '请输入', },
    // { type: 'input', label: '电话', prop: 'phone', span: 24, placeholder: '请输入' },
    // { type: 'input', label: '邮箱', prop: 'email', span: 24, placeholder: '请输入' },
    { type: 'select', label: '角色', prop: 'roleId', span: 24, placeholder: '请输入', options: jsOptions, },
    // { type: 'password', label: '新密码', prop: 'password', span: 24, placeholder: '请输入', },
    // { type: 'password', label: '确认新密码', prop: 'password2', span: 24, placeholder: '请输入', },
])
// 新增
const handAddAccount = () => {
    resetForm();
    Object.assign(ruleForm, {
        roleId: '0',
    });
    tableTitle.value = '请填写信息'
    formData = [
        { type: 'input', label: '用户名', prop: 'account', span: 24, placeholder: '请输入' },
        { type: 'input', label: '姓名', prop: 'adminName', span: 24, placeholder: '请输入' },
        { type: 'password', label: '密码', prop: 'password', span: 24, placeholder: '请输入' },
        { type: 'input', label: '电话', prop: 'phone', span: 24, placeholder: '请输入' },
        { type: 'input', label: '邮箱', prop: 'email', span: 24, placeholder: '请输入' },
        { type: 'select', label: '角色', prop: 'roleId', span: 24, placeholder: '请输入', options: jsOptions.value, },
    ]
    dialogVisible.value = true
}
// 编辑
const handEditAccount = (row: object, index: number) => {
    resetForm(row);
    tableTitle.value = '请编辑信息'
    formData = [
        // { type: 'input', label: '用户名', prop: 'account', span: 24, placeholder: '请输入' },
        // { type: 'input', label: '姓名', prop: 'adminName', span: 24, placeholder: '请输入' },
        { type: 'input', label: '电话', prop: 'phone', span: 24, placeholder: '请输入' },
        { type: 'input', label: '邮箱', prop: 'email', span: 24, placeholder: '请输入' },
        // { type: 'select', label: '角色', prop: 'roleId', span: 24, placeholder: '请输入', options: jsOptions.value, },
    ]
    dialogVisible.value = true
}
// 重置密码
const handDerivedPass = (row: object, index: number) => {
    resetForm(row);
    tableTitle.value = '重置密码'
    formData = [
        { type: 'password', label: '新密码', prop: 'password', span: 24, placeholder: '请输入', },
        { type: 'password', label: '确认新密码', prop: 'password2', span: 24, placeholder: '请输入', },
    ]
    dialogVisible.value = true
}
// 按钮组
const btnList = [
    { name: '查询', type: 'primary', click: handInquire, icon: '' },
    { name: '重置', type: 'success', click: handDerived, icon: '' },
]
const footerBtnList = [
    { name: '新增', type: 'primary', click: handAddAccount, icon: '' },
]
// 操作列按钮组
const btnListTable = ref([
    { name: '编辑', type: 'success', click: handEditAccount },
    { name: '重置密码', type: 'primary', click: handDerivedPass },
    { name: '删除', type: 'danger', click: del },
])
// 分页事件触发
const handlePageSize = (pageSize: number) => {// 每页大小
    // console.log('handlePageSize', pageSize);
    formBtnList.page_size = pageSize
    handInquire()
};
const handleCurrentPage = (currentPage: number) => {// 页码
    // console.log('handleCurrentPage', currentPage);
    formBtnList.page = currentPage
    handInquire()
};
// 表格相关 结束

// 弹窗相关
const dialogCom = ref<InstanceType<typeof DialogCom>>();
const btnLoading = ref(false)
// 表单校验配置
const rules = reactive<FormRules<RuleForm>>({
    admin_id: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
    ],
    account: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
        { max: 15, message: '用户名最多为15个字符', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
        { min: 8, message: '密码不能少于8位', trigger: 'blur' },
    ],
    adminName: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
    ],
    roleId: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
    ],
    // email: [
    //     { required: true, message: '此项为必填项', trigger: 'blur' },
    // ],
    phone: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
        { min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur' },
        {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
        },
    ],
    password2: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
        { min: 8, message: '密码不能少于8位', trigger: 'blur' },
    ],
})
// 弹窗 确认按钮
const submitForm = ((ruleFormData: any, tableTitle: string) => {
    // console.log(111, ruleFormData, tableTitle);
    if (tableTitle === '请填写信息') {
        let para = {
            // product_id: ruleFormData.product_id?.toString(),
            account: ruleFormData.account,
            adminName: ruleFormData.adminName,
            password: ruleFormData.password,
            phone: ruleFormData.phone,
            email: ruleFormData.email,
            roleId: Number(ruleFormData.roleId),
        }
        btnLoading.value = true
        authAdd(para).then((res: any) => {
            if (res.code === 200) {
                if (dialogCom.value) {
                    dialogCom.value.cancelClick(); // 调用子组件方法
                }
                ElMessage({
                    message: '成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(`请求错误: ${res.msg}`)
            }
        }).catch((error: any) => {
            ElMessage.error(`请求错误: ${error.msg}`)
            btnLoading.value = false
        }).finally(() => {
            btnLoading.value = false
            handInquire()
        })
    } else if (tableTitle === '请编辑信息') {
        let para = {
            adminId: ruleFormData.admin_id,
            // account: ruleFormData.account,
            // adminName: ruleFormData.adminName,
            phone: ruleFormData.phone,
            email: ruleFormData.email,
            // roleId: Number(ruleFormData.roleId),
        }
        btnLoading.value = true
        authEdit(para).then((res: any) => {
            if (res.code === 200) {
                if (dialogCom.value) {
                    dialogCom.value.cancelClick(); // 调用子组件方法
                }
                ElMessage({
                    message: '成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(`请求错误: ${res.msg}`)
            }
        }).catch((error: any) => {
            ElMessage.error(`请求错误: ${error.msg}`)
            btnLoading.value = false
        }).finally(() => {
            btnLoading.value = false
            handInquire()
        })
    } else if (tableTitle === '重置密码') {
        let para = {
            admin_id: ruleFormData.admin_id,
            password: ruleFormData.password,
            password2: ruleFormData.password2,
        }
        btnLoading.value = true
        resetPassword(para).then((res: any) => {
            if (res.code === 200) {
                if (dialogCom.value) {
                    dialogCom.value.cancelClick(); // 调用子组件方法
                }
                ElMessage({
                    message: '成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(`请求错误: ${res.msg}`)
            }
        }).catch((error: any) => {
            ElMessage.error(`请求错误: ${error.msg}`)
            btnLoading.value = false
        }).finally(() => {
            btnLoading.value = false
            handInquire()
        })
    }
})
// 标题
const tableTitle = ref('');
const dialogVisible = ref(false);
const beforeClose = () => {
    dialogVisible.value = false;
}
const dialogSwitch = (row: object) => {
    console.log('row: ', row);

}
onMounted(() => {
    handInquire()
})
</script>
<style lang='scss' scoped>
.demo-form-inline {
    .el-input {
        width: 265px;

    }

    :deep(.el-input__wrapper) {
        border-radius: 20px;
    }

}
</style>